package com.example.airport.parent;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;

import android.graphics.Typeface;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.administrator.dialoglibrary.ConfirmDialog;
import com.example.airport.ConfigActivity;
import com.example.airport.MainActivity;
import com.example.airport.R;
import com.example.airport.data.Air;
import com.example.airport.data.Book;
import com.example.airport.data.BookAdapter;
import com.example.airport.data.FixedSizeLinkedList;
import com.example.airport.data.Suggestion;
import com.example.airport.net.G;
import com.example.airport.net.datarequest.Http;
import com.example.airport.net.datarequest.IBack;
import com.example.airport.service.MyService;
import com.example.airport.utils.RandomAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.shawnlin.preferencesmanager.PreferencesManager;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.everything.android.ui.overscroll.OverScrollDecoratorHelper;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class MainFatherActivity extends  FatherActivity implements ICallback, IBack {

    @BindView(R.id.id_recycler_view)
    public RecyclerView recyclerView;



    public BookAdapter adapter;
    protected MyService myService = null;
    public Http userserverData=new Http(G.BASE_URL,"data",this,0);
    public FixedSizeLinkedList<Book> fixList=new FixedSizeLinkedList<>(G.MAX_LENGTH);

   // MqttClient pub_mqttClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setStatusBarView();
        toolbarInit();
        RecyclerViewInit();
       // long timestamp = System.currentTimeMillis();//生成时间戳

    }


    public void RecyclerViewInit()
    {
        adapter=new BookAdapter();
        LinearLayoutManager layoutManager=new LinearLayoutManager(this); //LinearLayoutManager中定制了可扩展的布局排列接口，子类按照接口中的规范来实现就可以定制出不同排雷方式的布局了
        recyclerView.setLayoutManager(layoutManager);
        OverScrollDecoratorHelper.setUpOverScroll(recyclerView, OverScrollDecoratorHelper.ORIENTATION_VERTICAL);
    }


    /***
     * 服务连接
     */
    public ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MyService.MyBinder myBinder = (MyService.MyBinder)service;
            myService = myBinder.getService();

            String username=PreferencesManager.getString("username",G.USERNAME);
            String password=PreferencesManager.getString("password",G.PASSWORD);
            String server=PreferencesManager.getString("server",G.BROKER_URL);
            String clientid=PreferencesManager.getString("clientid",G.CLIENTID);

            String topic_pilot=PreferencesManager.getString("topic_pilot",G.TOPIC_PILOT); //订阅飞行员
            String topic_aitrain_changeModel=PreferencesManager.getString("topic_change_model",G.TOPIC_AITRAIN_CHANGE_MODEL);  //订阅改变模式
            String topic_aitrain_anwser=PreferencesManager.getString("topic_answer",G.TOPIC_AITRAIN_ANSWER);
            String topic_aitrain_getModel=PreferencesManager.getString("topic_get_model",G.TOPIC_AITRAIN_GET_MODEL);

            String[] topics={topic_pilot,topic_aitrain_changeModel,topic_aitrain_anwser,topic_aitrain_getModel};
            int[] qoses={0,0,0,0};
            myService.getMqtt(MainFatherActivity.this,server, clientid,topics,qoses,username,password);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };



    /***
     * 向语义服务器，请求数据
     */
    protected void getCraftData(String text,String appmsg)
    {

        String robotid=PreferencesManager.getString("robotid",G.ROBOTID);
        String appkey=PreferencesManager.getString("appkey",G.APPKEY);
        String secret=PreferencesManager.getString("secret",G.SECRET);
        String sn=PreferencesManager.getString("sn",G.SN);
        String json="{\"robotid\":\""+robotid+"\",\"appkey\":\""+appkey+"\",\"secret\":\""+secret+"\",\"sn\":\""+sn+"\",\"text\":\""+ text +"\",\"appmsg\":\""+appmsg+"\"}";
        long timestamp = System.currentTimeMillis();//生成时间戳
        //System.out.println("timestamp:========"+timestamp);
        userserverData.httpPost(timestamp, RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),json));
    }



   protected Air dataAdapter(String json)
    {
        Gson gson=new Gson();
        Air air=null;
        try {
            air=gson.fromJson(json,Air.class);
        }catch (Exception e)
        {

        }

        return air;
    }

    /**
     * 从服务返回消息，在MainActivity,继承后，在UI线程显示
     * @param msg
     */
    @Override
    public void onSubscribedData(int type,String topic,String msg) { }

    /**
     * 页面显示时，mqtt启动服务
     */
    @Override
    protected void onStart() {
        super.onStart();
        toConnect();
    }

    protected  void toConnect()
    {
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, conn, BIND_AUTO_CREATE);
    }
    /**
     * 页面隐藏时，mqtt停止服务
     */
    @Override
    protected void onStop() {
        super.onStop();
        toDisConnect();
    }

    protected void toDisConnect()
    {
        unbindService(conn);
    }
    /**
     * 添加菜单
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //使用菜单填充器获取menu下的菜单资源文件
        getMenuInflater().inflate(R.menu.tool_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void success(int index, ResponseBody body) throws IOException {

    }

    @Override
    public void failure(int index, String msg) {

    }


    /**
     * 退出系统对话框
     *
     * @param keyCode
     * @param event
     * @return
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            String msg = getResources().getString(R.string.close_confirm_msg);
            leaveSystem(msg, false);
            return false;
        }
        return true;
    }

    /**
     * 退出系统
     *
     * @param str
     */
    protected void leaveSystem(String str, boolean ifClearPreference) {
        final ConfirmDialog confirmDialog = new ConfirmDialog(MainFatherActivity.this, getResources().getString(R.string.confirmDialog_title), str);
        confirmDialog.setOnDialogClickListener(new ConfirmDialog.OnDialogClickListener() {
            @Override
            public void onOKClick() {
                confirmDialog.dismiss();
                finish();
                if (ifClearPreference)
                    PreferencesManager.clear();
            }

            @Override
            public void onCancelClick() {
                confirmDialog.dismiss();
            }
        });
        confirmDialog.setCancelable(true);//点击空白处不消失
        confirmDialog.show();
    }


    protected void restoreSetting(String str) {
        final ConfirmDialog confirmDialog = new ConfirmDialog(MainFatherActivity.this, getResources().getString(R.string.confirmDialog_title), str);
        confirmDialog.setOnDialogClickListener(new ConfirmDialog.OnDialogClickListener() {
            @Override
            public void onOKClick() {
                 PreferencesManager.clear();
                Toast.makeText(getApplicationContext(), "配置已恢复！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelClick() {
                confirmDialog.dismiss();
            }
        });
        confirmDialog.setCancelable(true);//点击空白处不消失
        confirmDialog.show();
    }


}
